package com.rd.utils;


import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.rd.entity.RedisData;
import com.rd.entity.Shop;
import org.redisson.api.RBloomFilter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.time.LocalDateTime;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.function.Function;

// 缓存工具类
@Component
public class RedisCacheUtils {

    @Autowired
    StringRedisTemplate stringRedisTemplate;



    private static final ExecutorService es = Executors.newFixedThreadPool(10);




    // 解锁
    private void unLock(String key){
        stringRedisTemplate.delete(key);
    }

    //TODO 加锁并添加过期时间 boot2.1版本以上才支持
    private Boolean tryGetLock(String key){
        Boolean expire = stringRedisTemplate.opsForValue().setIfAbsent(key, "1",10, TimeUnit.SECONDS);
        System.out.println("expire:"+expire);
        return expire;
    }
    public void set(String key, Object value, Long time, TimeUnit timeUnit){
        stringRedisTemplate.opsForValue().set(key, JSONUtil.toJsonStr(value),time,timeUnit);
    }


    public void setWithLogicalExpire(String key, Object value, Long time, TimeUnit timeUnit){
        RedisData data = new RedisData();
        data.setData(value);
        data.setExpireTime(LocalDateTime.now().plusSeconds(time));
        stringRedisTemplate.opsForValue().set(key, JSONUtil.toJsonStr(data));
    }

    /**
     * 缓存空值解决缓存穿透
     * @param keyPrefix
     * @param id
     * @param time
     * @param timeUnit
     * @param type
     * @param dbFallback
     * @param <R>
     * @param <ID>
     * @return
     */
    public <R,ID> R queryWithPassThrough(String keyPrefix,  ID id,Long time, TimeUnit timeUnit, Class<R> type, Function<ID,R> dbFallback){
        String key = keyPrefix + id;
        // 查询缓存
        String json = stringRedisTemplate.opsForValue().get(key);
        if (StrUtil.isNotBlank(json)){
            return JSONUtil.toBean(json, type);
        }else if (json != null){
            return null;
        }
        // 使用回调函数，(调用者) 查询数据库
        R apply = dbFallback.apply(id);
        if (apply == null){
            // 若数据不存在，写入空值来应对缓存穿透
            stringRedisTemplate.opsForValue().set(key, "",2, TimeUnit.MINUTES);
            return null;
        }
        // 保存缓存到redis
        this.set(key, apply, time, timeUnit);
        return apply;
    }

    /**
     * 逻辑过期解决缓存击穿
     * @param keyPrefix
     * @param id
     * @param time
     * @param timeUnit
     * @param type
     * @param dbFallback
     * @param <R>
     * @param <ID>
     * @return
     */
    public <R,ID> R queryWithLogicalExpire(String keyPrefix,  ID id,Long time, TimeUnit timeUnit, Class<R> type, Function<ID,R> dbFallback){
        String key = keyPrefix + id;
        // 查询缓存
        String shopJson = stringRedisTemplate.opsForValue().get(key);
        // 缓存命中，先将json反序列化成对象
        RedisData  data = JSONUtil.toBean(shopJson, RedisData.class);
        JSONObject jsonData = (JSONObject) data.getData();
        R notExpireData = JSONUtil.toBean(jsonData, type);
        // 过期时间在当前时间之后，数据未过期，直接返回
        LocalDateTime expireTime = data.getExpireTime();
        if ( expireTime != null && expireTime.isAfter(LocalDateTime.now())){
            return notExpireData;
        }
        // 已过期，缓存重建
        String lockKey = "lock:shop:"+id;
        //获得互斥锁
        Boolean lock = tryGetLock(lockKey);
        //判断是否成功获得锁
        if(lock){
            //获取锁成功，开启独立线程，缓存重建
            es.submit(()->{
                try {
                    //回调
                    R apply = dbFallback.apply(id);
                    this.setWithLogicalExpire(key, apply, time,timeUnit);
                } catch (Exception e) {
                    e.printStackTrace();
                } finally {
                    // 释放锁
                    unLock(lockKey);
                }
            });
        }
        //返回旧的商铺信息
        return notExpireData;
    }



}
